package com.myqm.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; 
import com.alibaba.fastjson.JSON;
import com.myqm.annotation.LogAnnotation;
import com.myqm.pojo.sys.SysLogs;
import com.myqm.service.sys.SysLogsService;

import io.swagger.annotations.ApiOperation; 
/**
 * 统一日志处理
 * 
 */
@Aspect
@Component
public class LogAdvice {
	
	@Autowired
	private SysLogsService logService;

	@Around(value = "@annotation(com.myqm.annotation.LogAnnotation)")
	public Object logSave(ProceedingJoinPoint joinPoint) throws Throwable {
		SysLogs sysLogs = new SysLogs();
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		 
		String module = null;
		LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);
		module = logAnnotation.module();
		if (StringUtils.isEmpty(module)) {
			ApiOperation apiOperation = methodSignature.getMethod().getDeclaredAnnotation(ApiOperation.class);
			if (apiOperation != null) {
				module = apiOperation.value();
			}
		}

		if (StringUtils.isEmpty(module)) {
			throw new RuntimeException("not set module of operation!");
		}
		sysLogs.setModule(module);

		String params = "";  
		         if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {  
		              for ( int i = 0; i < joinPoint.getArgs().length; i++) {  
		                params += JSON.toJSONString(joinPoint.getArgs()[i]) + ";";  
		             }  
		        }   
		try {
			Object object = joinPoint.proceed(); 
			sysLogs.setFlag(true);
			sysLogs.setRemark(params);
			logService.save(sysLogs); 
			return object;
		} catch (Exception e) {
			sysLogs.setFlag(false);
			sysLogs.setRemark(e.getMessage());
			logService.save(sysLogs);
			throw e;
		}

	}
}
